<?php
// $Id: extcal_latest_func.php,v 0.12 2006/07/28 Exp $
//ExtCalendar Latest Events Module//
/**
* Content code
* @package Joonla! Open Source
* @subpackage ExtCalendar
* @copyright (C) 2000 - 2006
* @ All rights reserved
* @ Mambo Open Source is Free Software
* @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html
**/

/**
* ExtCalendar Latest Events Module
*
* 2006/07/28 - Version 0.1.2
*
* Module for displaying upcoming events in connection with the ExtCalendar
* component, available at extcalendar.mamboforge.net. The component must
* be installed before this module will work. There are some options for
* this module, which can be set in the "Parameters" section of the module
* in Administration.
*
*/

/* Deny direct access */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); 

######################################################################
#####  CUSTOM FUNCTIONS:
######################################################################

function sortUpcomingEvents( $a, $b ) {
    if ( strtotime($a->start_date) == strtotime($b->start_date) ) return 0;
	return ( strtotime($a->start_date) < strtotime($b->start_date) ) ? -1 : 1;
}

function mf_get_daterange_string($thisEvent) {

  global $EXTCAL_CONFIG;

  $no_end_specified = ( ($thisEvent->end_date == '0000-00-00 00:00:00') || ($thisEvent->end_date == '0000-00-00 00:00:01') || $EXTCAL_CONFIG['show_only_start_times'] ) ? true : false;

  $start_date_array = (explode('-',$thisEvent->start_date));
  $end_date_array = (explode('-',$thisEvent->end_date));
  $start_time_array = (explode(':',substr($thisEvent->start_date,10,15)));
  $end_time_array = (explode(':',substr($thisEvent->end_date,10,15)));
  // i.e. Fri-January-6-2005:
  $startdate = strftime("%a-%B-%d-%Y-%p", mktime($start_time_array[0], $start_time_array[1], 0, $start_date_array[1], $start_date_array[2], $start_date_array[0]));
  $enddate = strftime("%a-%B-%d-%Y-%p", mktime($end_time_array[0], $end_time_array[1], 0, $end_date_array[1], $end_date_array[2], $end_date_array[0]));
  $startdate = (explode('-',$startdate));
  $enddate = (explode('-',$enddate));

  $start_day = ucwords($startdate['0']);
  $start_month = ucwords($startdate['1']);
  $start_daynumber = intval($startdate['2']);
  $start_year = $startdate['3'];
  if ( $thisEvent->end_date == '0000-00-00 00:00:01' ) { // This event is an "All Day" event
    $start_time = EXTCAL_TEXT_ALL_DAY;
  }
  else {
    if ( !$EXTCAL_CONFIG['time_format_12_or_24'] ) { $start_time = date("H:i", mktime($start_time_array[0], $start_time_array[1], 0, 1, 1, 1975)); }
    else { $start_time = date("g:i", mktime($start_time_array[0], $start_time_array[1], 0, 1, 1, 1975)) . (($startdate['4'] == '') ? date(" a", mktime($start_time_array[0], $start_time_array[1], 0, 1, 1, 1975)) : ' '.strtolower($startdate['4'])); }
  }

  $end_day = ucwords($enddate['0']);
  $end_month = ucwords($enddate['1']);
  $end_daynumber = trim($enddate['2']);
  $end_year = $enddate['3'];
  if ( !$EXTCAL_CONFIG['time_format_12_or_24'] ) { $end_time = date("Hi", mktime($end_time_array[0], $end_time_array[1], 0, 1, 1, 1975)); }
  else { $end_time = date("g:i", mktime($end_time_array[0], $end_time_array[1], 0, 1, 1, 1975)) . (($enddate['4'] == '') ?  date(" a", mktime($start_time_array[0], $start_time_array[1], 0, 1, 1, 1975)) : ' '.strtolower($enddate['4']));}

  // If months are the same, return January 6-7, 2005. If not, return January 6 - February 7, 2005, if same year.
  if ( (($start_daynumber == $end_daynumber) && ($start_month == $end_month) && ($start_year == $end_year)) || $no_end_specified ) {
    $returnstring = $start_month . '&nbsp;' . $start_daynumber . ',&nbsp;' . $start_year;
	$returnstring .= ( $EXTCAL_CONFIG['show_times'] ) ? ' (' . $start_time . ( ($EXTCAL_CONFIG['show_times'] == 3 || $no_end_specified) ? '' : ' - ' . $end_time ) . ')' : '';
  } else if (($start_month == $end_month) && ($start_year == $end_year)) {
    if ( $EXTCAL_CONFIG['show_times'] ) {
      $returnstring = $start_month . '&nbsp;' . $start_daynumber . '&nbsp;(' . $start_time . ') - ' . $end_month . '&nbsp;' . $end_daynumber . ( ($EXTCAL_CONFIG['show_times'] == 3 || $no_end_specified) ? '' : '&nbsp;(' . $end_time . ')' )  . ',&nbsp;' . $start_year;
	} else {
      $returnstring = $start_month . '&nbsp;' . $start_daynumber . ' - ' . $end_daynumber . ',&nbsp;' . $start_year;
	}
  } else if ($start_year == $end_year) {
    if ( $EXTCAL_CONFIG['show_times'] ) {
      $returnstring = $start_month . '&nbsp;' . $start_daynumber . ' (' . $start_time . ') - ' . $end_month . ' ' . $end_daynumber . ( ($EXTCAL_CONFIG['show_times'] == 3 || $no_end_specified) ? '' : '&nbsp;(' . $end_time . ')' ) . ',&nbsp;' . $end_year;
	} else {
      $returnstring = $start_month . '&nbsp;' . $start_daynumber . ' - ' . $end_month . '&nbsp;' . $end_daynumber . ',&nbsp;' . $end_year;
	}
  } else {
    if ( $EXTCAL_CONFIG['show_times'] ) {
      $returnstring = $start_month . '&nbsp;' . $start_daynumber . ',&nbsp;' . $start_year . '&nbsp;(' . $start_time . ') - ' . $end_month . '&nbsp;' . $end_daynumber . ',&nbsp;' . $end_year . ( ($EXTCAL_CONFIG['show_times'] == 3 || $no_end_specified) ? '' : '&nbsp;(' . $end_time . ')' ) ;
	} else {
      $returnstring = $start_month . '&nbsp;' . $start_daynumber . ',&nbsp;' . $start_year . ' - ' . $end_month . '&nbsp;' . $end_daynumber . ',&nbsp;' . $end_year;
	}
  }
  return $returnstring;
}

function mf_shorten_with_ellipsis($inputstring,$characters) {
  return (strlen($inputstring) >= $characters) ? substr($inputstring,0,($characters-3)) . '...' : $inputstring;
}

function process_extcal_description($data)
{
/* Process message data with various conversions to eliminate bbcode and such*/

	global $EXTCAL_CONFIG;

	// Is BBCcode allowed in the Extcal settings?

	if (!$EXTCAL_CONFIG['strip_bbcode_from_description'])
	{

		$data = preg_replace("/\[B\](.*?)\[\/B\]/si", "<strong>\\1</strong>", $data);
		$data = preg_replace("/\[I\](.*?)\[\/I\]/si", "<em>\\1</em>", $data);
		$data = preg_replace("/\[U\](.*?)\[\/U\]/si", "<u>\\1</u>", $data);

		$data = preg_replace("/\[LEFT\](.*?)\[\/LEFT\]/si", "<div align='left'>\\1</div>", $data);
		$data = preg_replace("/\[CENTER\](.*?)\[\/CENTER\]/si", "<div align='center'>\\1</div>", $data);
		$data = preg_replace("/\[RIGHT\](.*?)\[\/RIGHT\]/si", "<div align='right'>\\1</div>", $data);

		$data = preg_replace("/\[URL\](http:\/\/)?(.*?)\[\/URL\]/si", "<A HREF=\"http://\\2\" target=\"_blank\">\\2</A>", $data);
		$data = preg_replace("/\[URL=(http:\/\/)?(.*?)\](.*?)\[\/URL\]/si", "<A HREF=\"http://\\2\" target=\"_blank\">\\3</A>", $data);
		$data = preg_replace("/\[EMAIL\](.*?)\[\/EMAIL\]/si", "<A HREF=\"mailto:\\1\" style=\"color:#446699\">\\1</A>", $data);
		$data = preg_replace("/\[IMG\](.*?)\[\/IMG\]/si", "<IMG border=0 SRC=\"\\1\">", $data);

		/* adding a space to beginning */
		$data = " ".$data;

		$data = preg_replace("#([\n ])([a-z]+?)://([^,<> \n\r]+)#i", "\\1<a href=\"\\2://\\3\" target=\"_blank\">\\2://\\3</a>", $data);

		$data = preg_replace("#([\n ])www\.([a-z0-9\-]+)\.([a-z0-9\-.\~]+)((?:/[^,<> \n\r]*)?)#i", "\\1<a href=\"http://www.\\2.\\3\\4\" target=\"_blank\">www.\\2.\\3\\4</a>", $data);

		$data = preg_replace("#([\n ])([a-z0-9\-_.]+?)@([^,<> \n\r]+)#i", "\\1<a href=\"mailto:\\2@\\3\">\\2@\\3</a>", $data);

		/* Remove space */
		$data = substr($data, 1);
  	        If ($EXTCAL_CONFIG['preserve_linebreaks'] == 1)
                  {                   
                   $data = nl2br_pre($data);
                  }

	} else {  // Remove code entirely when "Allow HTML" is disabled in Settings:
		$data = preg_replace("/\[B\](.*?)\[\/B\]/si", "$1", $data);
		$data = preg_replace("/\[I\](.*?)\[\/I\]/si", "$1", $data);
		$data = preg_replace("/\[U\](.*?)\[\/U\]/si", "$1", $data);

		$data = preg_replace("/\[LEFT\](.*?)\[\/LEFT\]/si", "$1", $data);
		$data = preg_replace("/\[CENTER\](.*?)\[\/CENTER\]/si", "$1", $data);
		$data = preg_replace("/\[RIGHT\](.*?)\[\/RIGHT\]/si", "$1", $data);

		$data = preg_replace("/\[URL\](http:\/\/)?(.*?)\[\/URL\]/si", "$2", $data);
		$data = preg_replace("/\[URL=(http:\/\/)?(.*?)\](.*?)\[\/URL\]/si", "$3", $data);
		$data = preg_replace("/\[EMAIL\](.*?)\[\/EMAIL\]/si", "$1", $data);
		$data = preg_replace("/\[IMG\](.*?)\[\/IMG\]/si", "$1", $data);

		If ($EXTCAL_CONFIG['preserve_linebreaks'] == 1)
                {
                  $data = nl2br_pre($data);
                }
	}
	return $data;

}

function add_recurrent_dates( $thisEvent, $maxDates, &$rowsToAdd, $whichtype ) {
	global $EXTCAL_CONFIG;

	// The idea with this function is to add all recurring events which have recurrences on or after
	// today, whether they *started* before today or not.

	$recurType = $thisEvent->recur_type;
	$recurInterval = (int)$thisEvent->recur_val;
	$recurEndDate = strtotime($thisEvent->recur_until);
	$recurEndType = (int)$thisEvent->recur_end_type;
	$recurEndCount = (int)$thisEvent->recur_count;

	// If the event only recurs up to a certain date (recur type 1 or 2) and that date has arrived, then forget it.
	if ( (($recurEndType == 1) || ($recurEndType == 2))  &&  $recurEndDate < $EXTCAL_CONFIG['today_stamp']  &&  $whichtype == 'upcoming' ) return;

	$eventNoEndSpecified = ( $thisEvent->end_date == '0000-00-00 00:00:00' ) ? true : false;
	$eventIsAllDay = ( $thisEvent->end_date == '0000-00-00 00:00:01' ) ? true : false;

	$startDay = (int)date("d", strtotime($thisEvent->start_date));
	$startMonth = (int)date("m", strtotime($thisEvent->start_date));
	$startYear = (int)date("Y", strtotime($thisEvent->start_date));
	$startHour = (int)date("H", strtotime($thisEvent->start_date));
	$startMinute = (int)date("i", strtotime($thisEvent->start_date));

	$endDay = (int)date("d", strtotime($thisEvent->end_date));
	$endMonth = (int)date("m", strtotime($thisEvent->end_date));
	$endYear = (int)date("Y", strtotime($thisEvent->end_date));
	$endHour = (int)date("H", strtotime($thisEvent->end_date));
	$endMinute = (int)date("i", strtotime($thisEvent->end_date));

	$startstamp = mktime($startHour,$startMinute,0,$startMonth,$startDay,$startYear);
	$duration = mktime($endHour,$endMinute,0,$endMonth,$endDay,$endYear) - $startstamp;
	$nextdatestamp = $startstamp;
	$number_of_recurrences_added = 0;

	while( $number_of_recurrences_added < $maxDates ) {

//MODIFIED: If we have reached Now + $EXTCAL_CONFIG['number_of_days_to_list_ahead'], stop the loop.
		if ( $whichtype == 'upcoming'  && $EXTCAL_CONFIG['number_of_days_to_list_ahead'] &&  $nextdatestamp > mktime(0, 0, 0, date("m")  , date("d")+$EXTCAL_CONFIG['number_of_days_to_list_ahead'], date("Y")) ) break;
		  // If enough recurrences have been added already, stop the loop.
		if ( $whichtype == 'upcoming'  &&  $number_of_recurrences_added >= $maxDates ) break;
		  // If we've reached the maximum number of recurrences, stop the loop.
		if ( $recurEndType == 1  &&  $number_of_recurrences_added >= $recurEndCount ) break;
		  // If we've reached the end date for recurrence, stop the loop.
		if ( $recurEndType == 2  &&  $nextdatestamp > $recurEndDate ) break;
		  // If we're in Recent Events and have passed today's date, stop the loop.
		if ( $whichtype == 'recent'  &&  $nextdatestamp >= $EXTCAL_CONFIG['now_stamp'] ) break;

		if ( $whichtype == 'upcoming'  &&  $nextdatestamp < $EXTCAL_CONFIG['now_stamp'] ) {
			$add_this_event = false;
		} else	{
			$thisEvent->start_date = date( 'Y-m-d H:i:s', $nextdatestamp );
			$thisEvent->end_date = date( 'Y-m-d H:i:s', $nextdatestamp + $duration );
			$add_this_event = true;
	    }

		if ( $add_this_event ) {
			if ( $eventNoEndSpecified ) $thisEvent->end_date = '0000-00-00 00:00:00';
			if ( $eventIsAllDay ) $thisEvent->end_date = '0000-00-00 00:00:01';
			$rowsToAdd[] = $thisEvent;
			$number_of_recurrences_added++;
		}

		// Increment the date to the next recurring date.
		// the mktime() function is smart and adjusts dates properly. For example, if the day number adds up to '33'
		// and there are only 30 days in the month, it will instead make it the 3rd day of the next month. Very cool.
		$thisMonth = (int)date( "m", $nextdatestamp );
		$thisDay = (int)date( "d", $nextdatestamp );
		$thisYear = (int)date( "Y", $nextdatestamp );
		switch($thisEvent->recur_type) {
			case "day":
					$nextdatestamp = mktime($startHour,$startMinute,0,$thisMonth,$thisDay+=$recurInterval,$thisYear);
					break;
			case "week":
					$nextdatestamp = mktime($startHour,$startMinute,0,$thisMonth,$thisDay+=$recurInterval*7,$thisYear);
					break;
			case "month":
					$nextdatestamp = mktime($startHour,$startMinute,0,$thisMonth+=$recurInterval,$thisDay,$thisYear);
					break;
			case "year":
					$nextdatestamp = mktime($startHour,$startMinute,0,$thisMonth,$thisDay,$thisYear+=$recurInterval);
					break;
			default:
		}
	}
}

function latest_has_priv($priv) {
    global $my;
/* returns true if the user has the privilege $priv */
// Revised to use new USER_IS_ADMIN global constant, which was set in config.inc.php
// using Mambo's usertype value. Does NOT have fancy code to allow "XXX type and up"
// to access page--just checks to see if you ARE that type or an Admin, and then lets
// you through. With one exception: if the privilege is set to "Registered" then anybody
// who's logged in gets through.

	if ($priv == "Anyone") { return true; }
	else if (($priv == "Registered") && USER_IS_LOGGED_IN) { return true; }
	else if (USER_IS_ADMIN || ($my->usertype == $priv)) { return true; }
	else { return false; }
}

function nl2br_pre($string, $wrap = 40) {
  $string = nl2br($string);

  preg_match_all("/<pre[^>]*?>(.|\n)*?<\/pre>/", $string, $pre1);

  for ($x = 0; $x < count($pre1[0]); $x++) {
   $pre2[$x] = preg_replace("/\s*<br[^>]*?>\s*/", "", $pre1[0][$x]);
   $pre2[$x] = preg_replace("/([^\n]{".$wrap."})(?!<\/pre>)(?!\n)/", "$1\n", $pre2[$x]);
   $pre1[0][$x] = "/".preg_quote($pre1[0][$x], "/")."/";
  }

  return preg_replace($pre1[0], $pre2, $string);
}


?>